<template>
  <div class="future-weather">
    <div>
      <h3>最后更新时间：{{ updateTime }}</h3>
    </div>
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import axios from 'axios'
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([GridComponent, LineChart, CanvasRenderer, UniversalTransition]);
import dayjs from 'dayjs'
import { KEY, API_24H } from '@/common/constants.js'
// 引入mapState函数
import { mapState } from 'vuex'

export default {
  data() {
    return {
      hourly: [],
      hourWeatherData: {
        fxTime: [],//x轴数据
        temp: [],//series数据
      },
      updateTime: ''
    }
  },
  computed: {
    // location: function () {
    //   return this.$store.state.location.id;
    // }
    ...mapState([
      "location"
    ])
  },
  methods: {
    // 获取API数据
    getData() {
      axios.get(API_24H, {
        params: {
          // location: "101010100",
          location: this.location.id,
          key: KEY,
        },
      }).then(res => {
        console.log(res.data);
        this.hourly = res.data.hourly;
        // 初始化图表数据(时间和温度两个数组)
        this.hourWeatherData.fxTime = []
        this.hourWeatherData.temp = []
        // 获取更新时间并使用dayjs库格式化
        this.updateTime = dayjs(res.data.updateTime).format("YYYY-MM-DD HH:mm:ss");
        // 遍历24小时天气预报，分别取出数据中的部分数据
        this.hourly.forEach(element => {
          this.hourWeatherData.fxTime.push(element.fxTime)
          this.hourWeatherData.temp.push(element.temp)
        });
        // 调用初始化图表方法
        this.initChart(this.hourWeatherData.fxTime.map((element) => dayjs(element).format("HH")),
          this.hourWeatherData.temp);
      })
    },
    // 初始化图表，有两个参数：x坐标的内容和图标值（y坐标）
    initChart(xAxisData, seriesData) {
      //此方法是通过js的dom获取网页元素，但是在vue中不能这么使用
      // var chartDom = document.getElementById("chartContainer");
      let chartDom = this.$refs.chartContainer;
      let myChart = echarts.init(chartDom)
      let option;
      option = {
        xAxis: {
          type: 'category',
          data: xAxisData,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesData,
            type: 'line',
            label: {
              show: true,
              position: 'top',
              formatter: (params) => {
                return params.value + '°C'
              }
            }
          },
        ],
      };
      option && myChart.setOption(option);
    }
  },
  mounted() {
    this.getData();
  },
  watch: {
    location: function () {
      // console.log("----------------location change")
      // 监听到location属性有变化的时候，重新调用getData()网络请求
      this.getData()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.chart-container {
  height: 20rem;
}
</style>
